package com.kt.mes.service.impl;

import com.kt.mes.domain.*;
import com.kt.mes.mapper.*;
import com.kt.mes.opc.OpcClientUtil;
import com.kt.mes.service.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

@Service
public class OpcServiceImpl implements IOpcService {
    @Autowired
    private WorkPlanMapper workPlanMapper;
    @Autowired
    private WorkPlanItemMapper workPlanItemMapper;
    @Autowired
    private ProcessRouteItemParamMapper processRouteItemParamMapper;
    @Autowired
    private OrderProductMapper orderProductMapperr;
    @Autowired
    private IProductStoreListService productStoreListService;

    @Autowired
    private IProductStoreService productStoreService;
    @Autowired
    private IStorageInRecordService storageInRecordService;

    @Autowired
    private StorageInRecordMapper storageInRecordMapper;

    @Autowired
    private IWasteStoreListService wasteStoreListService;


    @Autowired
    private ITraceDataService traceDataService; //追踪

    //根据工位查订单

    public void findOrder(String siteId) {
        //查询订单
        OrderProduct order_query = new OrderProduct();
        order_query.setOpState("N"); //查询正常订单
        List<OrderProduct> list_all_order = orderProductMapperr.selectOrderProductList(order_query);
        if (list_all_order.isEmpty() == false) {
            //遍历订单 选择合适的订单
            for (OrderProduct order : list_all_order) {


            }

        }


    }

    //根据 工位 和 托盘号 找工作计划
    @Override
    public FromMes findWorkPlanByTray(String siteId, int trayId, boolean last) {
        FromMes fromMes = new FromMes();

        fromMes.setFunSite("101" + siteId);
        //1.先找该托盘的任务
        WorkPlanItem wpi_query = new WorkPlanItem();
        wpi_query.setSiteId("gw" + siteId);
        wpi_query.setWpiState("N");
        wpi_query.setTrayId(trayId);
        WorkPlanItem wpi_first = new WorkPlanItem();

        List<WorkPlanItem> list_wpi = workPlanItemMapper.selectWorkPlanItemList(wpi_query);
      //  System.out.println("查询订单>");
        //System.out.println(list_wpi);

        if (!list_wpi.isEmpty() && list_wpi.size() == 1) {//找到任务
            wpi_first = list_wpi.get(0);

            //判断上一步是否完成
            WorkPlanItem wpi_gwlast = new WorkPlanItem();
            wpi_gwlast.setwId(wpi_first.getwId());
            wpi_gwlast.setOpId(wpi_first.getOpId());
            wpi_gwlast.setOpsNum(wpi_first.getOpsNum());
            wpi_gwlast.setStepNum(wpi_first.getStepNum() - 1);
            wpi_gwlast.setWpiState("N");

            if (last && !workPlanItemMapper.selectWorkPlanItemList(wpi_gwlast).isEmpty()) {
                System.out.println("上一步没完成");
                return fromMes;
            }


        } else {
            //2。再找第一步任务
            wpi_query.setTrayId(0);
            wpi_query.setStepNum(1);
            List<WorkPlanItem> list_wpi_first = workPlanItemMapper.selectWorkPlanItemList(wpi_query);
            if (!list_wpi_first.isEmpty()) {//找到任务
                wpi_first = list_wpi_first.get(0);

                //需要绑定托盘
                WorkPlanItem wpi_update = new WorkPlanItem();
                wpi_update.setTrayId(trayId);
                wpi_update.setOpId(wpi_first.getOpId());
                wpi_update.setOpsNum(wpi_first.getOpsNum());
                workPlanItemMapper.updateWorkPlanItemTray(wpi_update);

            } else {
                return fromMes;
            }

        }


        fromMes.setoId(wpi_first.getOpId());
        fromMes.setOposId(wpi_first.getOpsNum() + "");
        fromMes.setOpId(wpi_first.getActId());
        fromMes.setStepNum(wpi_first.getStepNum() + "");
        //找参数
        ProcessRouteItemParam processRouteItemParam = new ProcessRouteItemParam();
        processRouteItemParam.setTpriId(wpi_first.getTpriId());
        List<ProcessRouteItemParam> list_param = processRouteItemParamMapper.selectProcessRouteItemParamList(processRouteItemParam);
        if (list_param.isEmpty() == false) {

            for (int f = 0; f < list_param.size(); f++) {
                if (f == 0) {
                    fromMes.setParam01(list_param.get(f).getParamValue());
                }
                if (f == 1) {
                    fromMes.setParam02(list_param.get(f).getParamValue());
                }
            }
        }


        return fromMes;
    }


    //根据工位查询工作计划
    @Override
    public FromMes findWorkPlan(String siteId) {
        FromMes fromMes = new FromMes();
        fromMes.setFunSite("101" + siteId);
        //1.查询计划项目表
        WorkPlanItem wpi_query = new WorkPlanItem();
        wpi_query.setSiteId("gw" + siteId);
        wpi_query.setWpiState("N");
        List<WorkPlanItem> list_wpi = workPlanItemMapper.selectWorkPlanItemList(wpi_query);
        if (!list_wpi.isEmpty()) {

            WorkPlanItem wpi_first = list_wpi.get(0); //选第一个
            //  System.out.println(wpi_first);
            //判断上一步是否完成
            WorkPlanItem wpi_gwlast = new WorkPlanItem();
            wpi_gwlast.setwId(wpi_first.getwId());
            wpi_gwlast.setOpId(wpi_first.getOpId());
            wpi_gwlast.setOpsNum(wpi_first.getOpsNum());
            wpi_gwlast.setStepNum(wpi_first.getStepNum() - 1);
            wpi_gwlast.setWpiState("N");

            if (!workPlanItemMapper.selectWorkPlanItemList(wpi_gwlast).isEmpty()) {
                System.out.println("上一步没完成");
                return fromMes;
            }
            fromMes.setoId(wpi_first.getOpId());
            fromMes.setOposId(wpi_first.getOpsNum() + "");
            fromMes.setOpId(wpi_first.getActId());
            fromMes.setStepNum(wpi_first.getStepNum() + "");
            //找参数
            ProcessRouteItemParam processRouteItemParam = new ProcessRouteItemParam();
            processRouteItemParam.setTpriId(wpi_first.getTpriId());
            List<ProcessRouteItemParam> list_param = processRouteItemParamMapper.selectProcessRouteItemParamList(processRouteItemParam);
            if (list_param.isEmpty() == false) {

                for (int f = 0; f < list_param.size(); f++) {
                    if (f == 0) {
                        fromMes.setParam01(list_param.get(f).getParamValue());
                    }
                    if (f == 1) {
                        fromMes.setParam02(list_param.get(f).getParamValue());
                    }
                }
            }


        }


//        fromMes.setFunSite("101" + siteId);
//        // 查询计划表
//        WorkPlan wp = new WorkPlan();
//        wp.setWpState("N");
//        List<WorkPlan> list_wps = workPlanMapper.selectWorkPlanList(wp);
//        if (list_wps.isEmpty() == false) {
//            WorkPlan wp_first = list_wps.get(0);
//
//            WorkPlanItem wpi = new WorkPlanItem();
//            wpi.setwId(wp_first.getId());
//            wpi.setSiteId("gw" + siteId);
//            wpi.setWpiState("N");
//            List<WorkPlanItem> list_wpi = workPlanItemMapper.selectWorkPlanItemList(wpi);
//
//
//            if (list_wpi.isEmpty() == false) {
//                WorkPlanItem wpi_gw = list_wpi.get(0);
//                //判断上一步
//                WorkPlanItem wpi_gwlast = new WorkPlanItem();
//                wpi_gwlast.setwId(wp_first.getId());
//                wpi_gwlast.setOpsNum(wpi_gw.getOpsNum());
//                wpi_gwlast.setStepNum(wpi_gw.getStepNum() - 1);
//                wpi_gwlast.setWpiState("N");
//
//                if (!workPlanItemMapper.selectWorkPlanItemList(wpi_gwlast).isEmpty()) {
//                    System.out.println("上一步没完成");
//                    return fromMes;
//                }
//
//                fromMes.setoId(wpi_gw.getOpId());
//                fromMes.setOposId(wpi_gw.getOpsNum() + "");
//                fromMes.setOpId(wpi_gw.getActId());
//                fromMes.setStepNum(wpi_gw.getStepNum() + "");
//                //找参数
//                ProcessRouteItemParam processRouteItemParam = new ProcessRouteItemParam();
//                processRouteItemParam.setTpriId(wpi_gw.getTpriId());
//                List<ProcessRouteItemParam> list_param = processRouteItemParamMapper.selectProcessRouteItemParamList(processRouteItemParam);
//                if (list_param.isEmpty() == false) {
//
//                    for (int f = 0; f < list_param.size(); f++) {
//                        if (f == 0) {
//                            fromMes.setParam01(list_param.get(f).getParamValue());
//                        }
//                        if (f == 1) {
//                            fromMes.setParam02(list_param.get(f).getParamValue());
//                        }
//                    }
//                }
//
//            }
//        }

        return fromMes;
    }

    @Override
    public FromMes findWorkPlanAndTb(String siteId) {
        FromMes fromMes = new FromMes();

        fromMes.setFunSite("101" + siteId);
        //1.查询计划项目表
        WorkPlanItem wpi_query = new WorkPlanItem();
        wpi_query.setSiteId("gw" + siteId);
        wpi_query.setWpiState("N");
        List<WorkPlanItem> list_wpi = workPlanItemMapper.selectWorkPlanItemList(wpi_query);
        if (!list_wpi.isEmpty()) {

            WorkPlanItem wpi_first = list_wpi.get(0); //选第一个
            //判断上一步是否完成
            WorkPlanItem wpi_gwlast = new WorkPlanItem();
            wpi_gwlast.setwId(wpi_first.getId());
            wpi_gwlast.setOpId(wpi_first.getOpId());
            wpi_gwlast.setOpsNum(wpi_first.getOpsNum());
            wpi_gwlast.setStepNum(wpi_first.getStepNum() - 1);
            wpi_gwlast.setWpiState("N");
//            if (!workPlanItemMapper.selectWorkPlanItemList(wpi_gwlast).isEmpty()) {
//                System.out.println("上一步没完成");
//                return fromMes;
//            }
            fromMes.setoId(wpi_first.getOpId());
            fromMes.setOposId(wpi_first.getOpsNum() + "");
            fromMes.setOpId(wpi_first.getActId());
            fromMes.setStepNum(wpi_first.getStepNum() + "");
            //找参数
            ProcessRouteItemParam processRouteItemParam = new ProcessRouteItemParam();
            processRouteItemParam.setTpriId(wpi_first.getTpriId());
            List<ProcessRouteItemParam> list_param = processRouteItemParamMapper.selectProcessRouteItemParamList(processRouteItemParam);
            if (list_param.isEmpty() == false) {

                for (int f = 0; f < list_param.size(); f++) {
                    if (f == 0) {
                        fromMes.setParam01(list_param.get(f).getParamValue());
                    }
                    if (f == 1) {
                        fromMes.setParam02(list_param.get(f).getParamValue());
                    }
                }
            }


        }
//        // 查询计划表
//        WorkPlan wp = new WorkPlan();
//        wp.setWpState("N");
//        List<WorkPlan> list_wps = workPlanMapper.selectWorkPlanList(wp);
//        if (list_wps.isEmpty() == false) {
//            WorkPlan wp_first = list_wps.get(0);
//
//            WorkPlanItem wpi = new WorkPlanItem();
//            wpi.setwId(wp_first.getId());
//            wpi.setSiteId("gw" + siteId);
//            wpi.setWpiState("N");
//            List<WorkPlanItem> list_wpi = workPlanItemMapper.selectWorkPlanItemList(wpi);
//
//
//            if (list_wpi.isEmpty() == false) {
//                WorkPlanItem wpi_gw = list_wpi.get(0);
//                // 特殊情况 不判断上一步
////                WorkPlanItem wpi_gwlast=new WorkPlanItem();
////                wpi_gwlast.setwId(wp_first.getId());
////                wpi_gwlast.setOpsNum(wpi_gw.getOpsNum());
////                wpi_gwlast.setStepNum(wpi_gw.getStepNum()-1);
////                wpi_gwlast.setWpiState("N");
////
////                if(!workPlanItemMapper.selectWorkPlanItemList(wpi_gwlast).isEmpty()){
////                    System.out.println("上一步没完成");
////                    return fromMes;
////                }
//
//                fromMes.setoId(wpi_gw.getOpId());
//                fromMes.setOposId(wpi_gw.getOpsNum() + "");
//                fromMes.setOpId(wpi_gw.getActId());
//                fromMes.setStepNum(wpi_gw.getStepNum() + "");
//                //找参数
//                ProcessRouteItemParam processRouteItemParam = new ProcessRouteItemParam();
//                processRouteItemParam.setTpriId(wpi_gw.getTpriId());
//                List<ProcessRouteItemParam> list_param = processRouteItemParamMapper.selectProcessRouteItemParamList(processRouteItemParam);
//                if (list_param.isEmpty() == false) {
//
//                    for (int f = 0; f < list_param.size(); f++) {
//                        if (f == 0) {
//                            fromMes.setParam01(list_param.get(f).getParamValue());
//                        }
//                        if (f == 1) {
//                            fromMes.setParam02(list_param.get(f).getParamValue());
//                        }
//                    }
//                }
//
//            }
//        }

        return fromMes;
    }

    @Override
    public void updateWpAndWpiAndOp(ToMes toMes) {

        WorkPlanItem wpi = new WorkPlanItem();
        wpi.setOpId(toMes.getoId());
        wpi.setOpsNum(Integer.valueOf(toMes.getOposId()));
        wpi.setActId(toMes.getOpId());
        wpi.setStepNum(Integer.valueOf(toMes.getStepNum()));
        wpi.setTrayId(Integer.valueOf(toMes.getTrayId()));
        List<WorkPlanItem> list_wpi = workPlanItemMapper.selectWorkPlanItemList(wpi);
        // System.out.println(list_wpi);
        if (list_wpi.isEmpty() == false) {
            WorkPlanItem updateWorkPlanItem = new WorkPlanItem();
            updateWorkPlanItem.setId(list_wpi.get(0).getId());
            updateWorkPlanItem.setWpiState("RUN");
            updateWorkPlanItem.setBeginTime(new Date());
            workPlanItemMapper.updateWorkPlanItem(updateWorkPlanItem);
            //(2) 计划状态

            WorkPlan updateWp = workPlanMapper.selectWorkPlanById(list_wpi.get(0).getwId());
            if (updateWp.getBeginTime() == null) {
                updateWp.setBeginTime(new Date());
            }
            // updateWp.setWpState("RUN");
            workPlanMapper.updateWorkPlan(updateWp);

            //（3）订单状态
            OrderProduct orderProduct = new OrderProduct();
            orderProduct.setOpId(updateWp.getoId());
            List<OrderProduct> list_order = orderProductMapperr.selectOrderProductList(orderProduct);
            if (list_order.isEmpty() == false) {
                OrderProduct updateOrderProduct = list_order.get(0);
                if (updateOrderProduct.getStartTime() == null) {
                    updateOrderProduct.setStartTime(new Date());
                }
                updateOrderProduct.setOpState("R");
                orderProductMapperr.updateOrderProduct(updateOrderProduct);
            }
        }


    }

    @Override
    public void finWpAndWpiAndOp(ToMes toMes) {
        //2.修改状态
        //(1) 子计划状态
        WorkPlanItem wpi = new WorkPlanItem();

        wpi.setOpId(toMes.getoId());
        wpi.setOpsNum(Integer.valueOf(toMes.getOposId()));
        wpi.setActId(toMes.getOpId());
        wpi.setStepNum(Integer.valueOf(toMes.getStepNum()));
        List<WorkPlanItem> list_wpi = workPlanItemMapper.selectWorkPlanItemList(wpi);
        if (list_wpi.isEmpty() == false) {
            WorkPlanItem updateWorkPlanItem = new WorkPlanItem();
            updateWorkPlanItem.setId(list_wpi.get(0).getId());
            updateWorkPlanItem.setWpiState("FIN");
            updateWorkPlanItem.setEndTime(new Date());
            workPlanItemMapper.updateWorkPlanItem(updateWorkPlanItem);
            //(2) 计划状态(子计划完成)

            WorkPlan updateWp = workPlanMapper.selectWorkPlanById(list_wpi.get(0).getwId());
            //轮询子计划
            for (int t = 0; t < updateWp.getSumPos(); t++) {
                WorkPlanItem wpiq = new WorkPlanItem();
                wpiq.setwId(updateWp.getId());
                wpiq.setOpsNum(t + 1);
                List<WorkPlanItem> allWpi = workPlanItemMapper.selectWorkPlanItemList(wpiq);
                wpiq.setWpiState("FIN");
                List<WorkPlanItem> finWpi = workPlanItemMapper.selectWorkPlanItemList(wpiq);

                if (allWpi.size() == finWpi.size()) {
                    updateWp.setFinPos(t + 1);
                }

            }
            if (updateWp.getFinPos() == updateWp.getSumPos()) {  //全部完成
                updateWp.setEndTime(new Date());
                updateWp.setWpState("FIN");
            }
            workPlanMapper.updateWorkPlan(updateWp);

            //（3）订单状态
            OrderProduct orderProduct = new OrderProduct();
            orderProduct.setOpId(updateWp.getoId());
            List<OrderProduct> list_order = orderProductMapperr.selectOrderProductList(orderProduct);
            if (list_order.isEmpty() == false) {
                OrderProduct updateOrderProduct = list_order.get(0);
                updateOrderProduct.setFinQty(updateWp.getFinPos());
                if (updateOrderProduct.getFinQty() == updateOrderProduct.getProQty()) {
                    updateOrderProduct.setEndTime(new Date());
                    updateOrderProduct.setOpState("F");
                }

                orderProductMapperr.updateOrderProduct(updateOrderProduct);


                //放入追踪数据
                TraceData traceData=new TraceData();
                traceData.setoId(toMes.getoId()); //订单号
                traceData.setPosId(toMes.getOposId()); //子订单号
                traceData.setTrayId(toMes.getTrayId());
                traceData.setProName(updateOrderProduct.getPpName());
                traceData.setTraceId(toMes.getoId()+"-"+toMes.getOposId());//追踪码
                traceData.setActName(toMes.getOpId()+"-"+list_wpi.get(0).getActName());//动作名称
                traceData.setBillTime(new Date());

                traceDataService.insertTraceData(traceData);

            }



        }

        //放入追踪数据



    }

    @Override
    public void finWpAndWpiAndRk(ToMes toMes) {


    }

    @Override
    public void finAndUnWpAndWpiAndOp(ToMes toMes) {

        //订单不合格品加 1
        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setOpId(toMes.getoId());
        List<OrderProduct> list_order = orderProductMapperr.selectOrderProductList(orderProduct);
        if (list_order.isEmpty() == false && list_order.size()==1) {
            OrderProduct updateOrderProduct = list_order.get(0);
            updateOrderProduct.setBadQty(updateOrderProduct.getBadQty()+1);

            orderProductMapperr.updateOrderProduct(updateOrderProduct);

            //入废品库
            WasteStoreList wasteStoreList=new WasteStoreList();
            wasteStoreList.setTwsId(1L);
            wasteStoreList.setAvaQty(1L);
            wasteStoreList.setCreateTime(new Date());
            wasteStoreList.setmId(updateOrderProduct.getPpId());
            wasteStoreListService.insertWasteStoreList(wasteStoreList);

            //入库记录
            StorageInRecord storageInRecord=new StorageInRecord();
            storageInRecord.setRkId("RK"+ DateUtils.dateTimeNow());
            storageInRecord.setmId(updateOrderProduct.getPpId());
            storageInRecord.setRkQty(1);
            storageInRecord.setOrderId(updateOrderProduct.getOpId());
            storageInRecord.setCreateTime(DateUtils.getNowDate());
            storageInRecord.setRkType("废品入库");
            //storageInRecord.setRkPos(areaNum+" 号库位");
            storageInRecordMapper.insertStorageInRecord(storageInRecord);

        }


       //
        WorkPlanItem wpi = new WorkPlanItem();

        wpi.setOpId(toMes.getoId());
        wpi.setOpsNum(Integer.valueOf(toMes.getOposId()));
        List<WorkPlanItem> list_wpi_last = workPlanItemMapper.selectWorkPlanItemList(wpi);

        list_wpi_last.forEach(v -> {

            if (v.getWpiState().equals("N")) {
                v.setWpiState("FIN");
                workPlanItemMapper.updateWorkPlanItem(v);
            }


        });

        finWpAndWpiAndOp(toMes);
//
//        wpi.setActId(toMes.getOpId());
//        wpi.setStepNum(Integer.valueOf(toMes.getStepNum()));
//        List<WorkPlanItem> list_wpi = workPlanItemMapper.selectWorkPlanItemList(wpi);
//        if (list_wpi.isEmpty() == false) {
//
//
//            WorkPlanItem wpi_gw = list_wpi.get(0);
//            wpi_gw.setWpiState("FIN");
//            wpi_gw.setEndTime(new Date());
//            workPlanItemMapper.updateWorkPlanItem(wpi_gw);
//
//            list_wpi_last.forEach(v -> {
//
//                if(v.getWpiState().equals("N")){
//                    v.setWpiState("FIN_UN");
//                    workPlanItemMapper.updateWorkPlanItem(v);
//                }
//
//
//            });
//
//            // 1.工作计划终止
//            WorkPlan wp = new WorkPlan();
//            wp.setId(wpi_gw.getwId());
//            wp.setEndTime(new Date());
//            wp.setWpState("FIN_UN"); //完成 但不合格
//            workPlanMapper.updateWorkPlan(wp);
//
//            //2.订单完成
//
//            OrderProduct orderProduct = new OrderProduct();
//            orderProduct.setOpId(wpi_gw.getOpId());
//            List<OrderProduct> list_order = orderProductMapperr.selectOrderProductList(orderProduct);
//            if (list_order.isEmpty() == false) {
//                OrderProduct updateOrderProduct = list_order.get(0);
//                updateOrderProduct.setOpState("FIN_UN");
//                updateOrderProduct.setEndTime(new Date());
//
//                orderProductMapperr.updateOrderProduct(updateOrderProduct);
//            }
//
//
//        }


    }

    @Override
    public void writeOpc(OpcUaClient opc, FromMes fromMes, OpcNode opcNode) {
        //2 写数据
        OpcClientUtil.write(opcNode.node_fun_site_FROMMES, fromMes.getFunSite(), opc); //功能号
        OpcClientUtil.write(opcNode.node_oid_FROMMES, fromMes.getoId(), opc);//订单号
        OpcClientUtil.write(opcNode.node_oposid_FROMMES, fromMes.getOposId(), opc); //子订单号
        OpcClientUtil.write(opcNode.node_opid_FROMMES, fromMes.getOpId(), opc);//操作号
        OpcClientUtil.write(opcNode.node_step_num_FROMMES, fromMes.getStepNum(), opc);//步骤号
        OpcClientUtil.write(opcNode.node_param01_FROMMES, fromMes.getParam01(), opc);//参数1
        OpcClientUtil.write(opcNode.node_param02_FROMMES, fromMes.getParam02(), opc);//参数2
    }

    @Override
    public void writeOpc(OpcUaClient opc, FromMes fromMes, NodeId node_fun_site_FROMMES, NodeId node_oid_FROMMES, NodeId node_oposid_FROMMES, NodeId node_opid_FROMMES, NodeId node_step_num_FROMMES, NodeId node_param01_FROMMES, NodeId node_param02_FROMMES) {


        //2 写数据
        OpcClientUtil.write(node_fun_site_FROMMES, fromMes.getFunSite(), opc); //功能号
        OpcClientUtil.write(node_oid_FROMMES, fromMes.getoId(), opc);//订单号
        OpcClientUtil.write(node_oposid_FROMMES, fromMes.getOposId(), opc); //子订单号
        OpcClientUtil.write(node_opid_FROMMES, fromMes.getOpId(), opc);//操作号
        OpcClientUtil.write(node_step_num_FROMMES, fromMes.getStepNum(), opc);//步骤号
        OpcClientUtil.write(node_param01_FROMMES, fromMes.getParam01(), opc);//参数1
        OpcClientUtil.write(node_param02_FROMMES, fromMes.getParam02(), opc);//参数2
    }

    @Override
    public ToMes readOpc(OpcUaClient opc, OpcNode opcNode) {
        ToMes toMes = new ToMes();

        String oId = OpcClientUtil.read(opcNode.node_oid_TOMES, opc);
        String oposId = OpcClientUtil.read(opcNode.node_oposid_TOMES, opc);
        String opId = OpcClientUtil.read(opcNode.node_opid_TOMES, opc);
        String stepNum = OpcClientUtil.read(opcNode.node_step_num_TOMES, opc);
        String trayId = OpcClientUtil.read(opcNode.node_tray_id_TOMES, opc);
        int areaNum = 0;
        try {
            areaNum = Integer.valueOf(OpcClientUtil.read(opcNode.node_area_num_TOMES, opc));
        } catch (Exception e) {
            System.out.println("没有此节点");
        }


        toMes.setoId(oId);
        toMes.setOposId(oposId);
        toMes.setOpId(opId);
        toMes.setStepNum(stepNum);
        toMes.setTrayId(trayId);
        toMes.setAreaNum(areaNum);

        return toMes;
    }

    @Override
    public ToMes readOpc(OpcUaClient opc, NodeId node_oid_TOMES, NodeId node_oposid_TOMES, NodeId node_opid_TOMES, NodeId node_step_num_TOMES, NodeId node_tray_id) {

        ToMes toMes = new ToMes();


        String oId = OpcClientUtil.read(node_oid_TOMES, opc);
        String oposId = OpcClientUtil.read(node_oposid_TOMES, opc);
        String opId = OpcClientUtil.read(node_opid_TOMES, opc);
        String stepNum = OpcClientUtil.read(node_step_num_TOMES, opc);
        String trayId = OpcClientUtil.read(node_tray_id, opc);

        toMes.setoId(oId);
        toMes.setOposId(oposId);
        toMes.setOpId(opId);
        toMes.setStepNum(stepNum);
        toMes.setTrayId(trayId);

        return toMes;
    }


    @Override
    public void resetOpc(OpcUaClient opc, OpcNode opcNode) {
        OpcClientUtil.write(opcNode.node_fun_TOMES, "0", opc);
        OpcClientUtil.write(opcNode.node_oid_TOMES, "0", opc);
        OpcClientUtil.write(opcNode.node_oposid_TOMES, "0", opc);
        OpcClientUtil.write(opcNode.node_opid_TOMES, "0", opc);
        OpcClientUtil.write(opcNode.node_step_num_TOMES, "0", opc);
        OpcClientUtil.write(opcNode.node_tray_id_TOMES, "0", opc);

        OpcClientUtil.write(opcNode.node_area_num_TOMES, 0, opc);


    }

    @Override
    public void resetOpc(OpcUaClient opc, NodeId node_fun_TOMES, NodeId node_oid_TOMES, NodeId node_oposid_TOMES, NodeId node_opid_TOMES, NodeId node_step_num_TOMES, NodeId node_tray_id) {
        OpcClientUtil.write(node_fun_TOMES, "0", opc);
        OpcClientUtil.write(node_oid_TOMES, "0", opc);
        OpcClientUtil.write(node_oposid_TOMES, "0", opc);
        OpcClientUtil.write(node_opid_TOMES, "0", opc);
        OpcClientUtil.write(node_step_num_TOMES, "0", opc);
        OpcClientUtil.write(node_tray_id, "0", opc);
    }

//    @Override
//    public void printLight(String contentS,String codeStr) {
//        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
//        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//        // 创建Post请求
//        HttpPost httpPost = new HttpPost("http://192.168.43.1/changetext_p.php");
//
//
//        //声明list集合，用来分装表单中的参数
//        //要求：设置请求的地址是：http://yun.itheima.com/search?keys=java
//        List<NameValuePair> params = new ArrayList<NameValuePair>();
//        System.out.println(contentS);
//        params.add(new BasicNameValuePair("labelName", "文本"));
//        params.add(new BasicNameValuePair("content", contentS));
//
//        params.add(new BasicNameValuePair("labelName", "文本1"));
//        params.add(new BasicNameValuePair("content", codeStr));
//        // 创建表单的Entity对象,第一个参数是封装好的表单数据，第二个参数就是编码方式
//        UrlEncodedFormEntity formEntity = null;
//        try {
//            formEntity = new UrlEncodedFormEntity(params, "utf8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        //设置表单的Entity对象到Post请求中
//        httpPost.setEntity(formEntity);
//
//
//        //使用httpClient发起响应获取repsonse
//        CloseableHttpResponse response = null;
//        try {
//            response = httpClient.execute(httpPost);
//            //4.解析响应，获取数据
//            //判断状态码是否是200
//            if (response.getStatusLine().getStatusCode() == 200) {
//                HttpEntity httpEntity = response.getEntity();
//                String content = EntityUtils.toString(httpEntity, "utf8");
//                //System.out.println(content.length());
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                response.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            try {
//                httpClient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//
//
//    }
    @Override
    public void printLight(String labelName,String contentStr) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost("http://192.168.43.1/changetext_p.php");


        //声明list集合，用来分装表单中的参数
        //要求：设置请求的地址是：http://yun.itheima.com/search?keys=java
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("labelName", labelName));
        params.add(new BasicNameValuePair("content", contentStr));


        // 创建表单的Entity对象,第一个参数是封装好的表单数据，第二个参数就是编码方式
        UrlEncodedFormEntity formEntity = null;
        try {
            formEntity = new UrlEncodedFormEntity(params, "utf8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //设置表单的Entity对象到Post请求中
        httpPost.setEntity(formEntity);


        //使用httpClient发起响应获取repsonse
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            //4.解析响应，获取数据
            //判断状态码是否是200
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                String content = EntityUtils.toString(httpEntity, "utf8");
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    @Override
    public FromMes findParam(ToMes toMes) {

        FromMes fromMes = new FromMes();

        WorkPlanItem wpi_query = new WorkPlanItem();
        wpi_query.setOpId(toMes.getoId());
        wpi_query.setOpsNum(Integer.valueOf(toMes.getOposId()));
        wpi_query.setActId(toMes.getOpId());
        wpi_query.setStepNum(Integer.valueOf(toMes.getStepNum()));


        List<WorkPlanItem> list = workPlanItemMapper.selectWorkPlanItemList(wpi_query);

        if (!list.isEmpty()) {
            WorkPlanItem wpi_gw = list.get(0);
            //找参数
            ProcessRouteItemParam processRouteItemParam = new ProcessRouteItemParam();
            processRouteItemParam.setTpriId(wpi_gw.getTpriId());
            List<ProcessRouteItemParam> list_param = processRouteItemParamMapper.selectProcessRouteItemParamList(processRouteItemParam);
            if (list_param.isEmpty() == false) {

                for (int f = 0; f < list_param.size(); f++) {
                    if (f == 0) {
                        fromMes.setParam01(list_param.get(f).getParamValue());
                    }
                    if (f == 1) {
                        fromMes.setParam02(list_param.get(f).getParamValue());
                    }
                }
            }
        }


        return fromMes;


    }

    @Override
    public boolean addFileToUpan(String url, String fileName) {
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;


        try {
            System.out.println("录入开始！");
            // 建立链接
            URL httpUrl = new URL("http://localhost:8080" + url);
            conn = (HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单，默认get方式
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);


            //写入到文件（注意文件保存路径的后面一定要加上文件的名称）
            fileOut = new FileOutputStream("F:" + fileName);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            //保存文件
            while (length != -1) {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
            conn.disconnect();
            System.out.println("录入完成！");

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("抛出异常！！");
            return false;
        }


    }

    //完成6工位入成品库
    @Override
    public void productStoreIn(String oId) {
        //确定位置（1-9）自动寻位
        ProductStore productStore = new ProductStore();
        productStore.setStatus("0");
        List<ProductStore> list_ps = productStoreService.selectProductStoreList(productStore); //搜索正常库位

        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setOpId(oId);
        List<OrderProduct> list_op = orderProductMapperr.selectOrderProductList(orderProduct); //查询订单

        if (!list_ps.isEmpty() && !list_op.isEmpty()) {
            ProductStore ps_check = list_ps.get(0); //找到一个库位
            OrderProduct op = list_op.get(0);//找到订单信息


            //入库
            ProductStoreList productStoreList = new ProductStoreList();
            productStoreList.setTpsId(ps_check.getId());
            productStoreList.setmId(op.getPpId());
            productStoreList.setAvaQty(1L); //默认都是一个
            productStoreList.setCreateTime(new Date());

            //入库记录
            StorageInRecord storageInRecord = new StorageInRecord();
            storageInRecord.setRkId("RK" + op.getOpId());
            storageInRecord.setmId(op.getPpId());
            storageInRecord.setRkQty(1);
            storageInRecord.setRkType("成品入库");
            storageInRecord.setCreateTime(new Date());

            storageInRecordService.insertStorageInRecord(storageInRecord);
            productStoreListService.insertProductStoreList(productStoreList);

            //更新库位状态
            ps_check.setStatus("1");
            productStoreService.updateProductStore(ps_check);

            //  productStoreListService.selectProductStoreListList();

        }


        //2 入库记录


    }

    @Override
    public List<Map<String,Object>> opcNodeToMap(OpcNode opcNode,FromMes fromMes){
        Map<String,Object> nodeMap_fun_site_FROMMES=new HashMap<>();
        Map<String,Object> nodeMap_oid_FROMMES=new HashMap<>();
        Map<String,Object> nodeMap_oposid_FROMMES=new HashMap<>();
        Map<String,Object> nodeMap_opid_FROMMES=new HashMap<>();
        Map<String,Object> nodeMap_step_num_FROMMES=new HashMap<>();
        Map<String,Object> nodeMap_param01_FROMMES=new HashMap<>();
        Map<String,Object> nodeMap_param02_FROMMES=new HashMap<>();


        //功能号
        nodeMap_fun_site_FROMMES.put("id",opcNode.node_fun_site_FROMMES.toParseableString());
        nodeMap_fun_site_FROMMES.put("value",fromMes.getFunSite());

        //订单号
        nodeMap_oid_FROMMES.put("id",opcNode.node_oid_FROMMES.toParseableString());
        nodeMap_oid_FROMMES.put("value",fromMes.getoId());


       //子订单号
        nodeMap_oposid_FROMMES.put("id",opcNode.node_oposid_FROMMES.toParseableString());
        nodeMap_oposid_FROMMES.put("value",fromMes.getOposId());

        //操作号
        nodeMap_opid_FROMMES.put("id",opcNode.node_opid_FROMMES.toParseableString());
        nodeMap_opid_FROMMES.put("value",fromMes.getOpId());



//      OpcClientUtil.write(node_step_num_FROMMES, fromMes.getStepNum(), opc);//步骤号
        nodeMap_step_num_FROMMES.put("id",opcNode.node_step_num_FROMMES.toParseableString());
        nodeMap_step_num_FROMMES.put("value",fromMes.getStepNum());

//      //参数1
        nodeMap_param01_FROMMES.put("id",opcNode.node_param01_FROMMES.toParseableString());
        nodeMap_param01_FROMMES.put("value",fromMes.getParam01());
//      //参数2
        nodeMap_param02_FROMMES.put("id",opcNode.node_param02_FROMMES.toParseableString());
        nodeMap_param02_FROMMES.put("value",fromMes.getParam02());


        List<Map<String,Object>> list=new ArrayList<>();
        list.add(nodeMap_fun_site_FROMMES);
        list.add(nodeMap_oid_FROMMES);
        list.add(nodeMap_oposid_FROMMES);
        list.add(nodeMap_opid_FROMMES);
        list.add(nodeMap_step_num_FROMMES);
        list.add(nodeMap_param01_FROMMES);
        list.add(nodeMap_param02_FROMMES);

            return list;
    }

    @Override
    public List<Map<String,Object>> opcNodeToMap(OpcNode opcNode,ToMes toMes){
        Map<String,Object> nodeMap_fun_site_TOMES=new HashMap<>();
        Map<String,Object> nodeMap_oid_TOMES=new HashMap<>();
        Map<String,Object> nodeMap_oposid_TOMES=new HashMap<>();
        Map<String,Object> nodeMap_opid_TOMES=new HashMap<>();
        Map<String,Object> nodeMap_step_num_TOMES=new HashMap<>();
        Map<String,Object> nodeMap_tray_id_TOMES=new HashMap<>();



        //功能号
        nodeMap_fun_site_TOMES.put("id",opcNode.node_fun_TOMES.toParseableString());
        nodeMap_fun_site_TOMES.put("value",toMes.getFunSite());

        //订单号
        nodeMap_oid_TOMES.put("id",opcNode.node_oid_TOMES.toParseableString());
        nodeMap_oid_TOMES.put("value",toMes.getoId());


        //子订单号
        nodeMap_oposid_TOMES.put("id",opcNode.node_oposid_TOMES.toParseableString());
        nodeMap_oposid_TOMES.put("value",toMes.getOposId());

        //操作号
        nodeMap_opid_TOMES.put("id",opcNode.node_opid_TOMES.toParseableString());
        nodeMap_opid_TOMES.put("value",toMes.getOpId());



//      OpcClientUtil.write(node_step_num_FROMMES, fromMes.getStepNum(), opc);//步骤号
        nodeMap_step_num_TOMES.put("id",opcNode.node_step_num_TOMES.toParseableString());
        nodeMap_step_num_TOMES.put("value",toMes.getStepNum());

//      //托盘号
        nodeMap_tray_id_TOMES.put("id",opcNode.node_tray_id_TOMES.toParseableString());
        nodeMap_tray_id_TOMES.put("value",toMes.getTrayId());



        List<Map<String,Object>> list=new ArrayList<>();
        list.add(nodeMap_fun_site_TOMES);
        list.add(nodeMap_oid_TOMES);
        list.add(nodeMap_oposid_TOMES);
        list.add(nodeMap_opid_TOMES);
        list.add(nodeMap_step_num_TOMES);
        list.add(nodeMap_tray_id_TOMES);


        return list;
    }


    public static void main(String[] args) {
//        OpcNode opcNode=new OpcNode(1);
//        System.out.println(opcNode.node_fun_site_FROMMES.toParseableString());
       // new OpcServiceImpl().addFileToUpan("/profile/upload/2021/03/19/14f676d5-58b9-4ffd-905e-c668f19357c5.mp3", "0001MES.mp3");

      //  new OpcServiceImpl().printLight("文本","中船监控");
       // new OpcServiceImpl().printLight("文本1","20210615004-4");

       HttpUtils.sendPost("http://192.168.43.1/changetext_p.php","labelName=文本&content=测试东西");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        HttpUtils.sendPost("http://192.168.43.1/changetext_p.php","labelName=文本1&content=20210615004-2");

                //      params.add(new BasicNameValuePair("labelName", labelName));
        //        params.add(new BasicNameValuePair("content", contentStr));

    }
}
